package com.example.test.service;

import com.example.test.bean.DTO.UserAddressDTO;
import com.example.test.bean.VO.UserAddressVO;
import com.example.test.bean.domain.UserAddress;

import com.example.test.exception.BusinessException;
import com.example.test.mapper.UserAddressMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserAddressService {

	@Resource
	private UserAddressMapper userAddressMapper;

	/**
	 * 添加用户地址
	 */
	public void addAddress(UserAddressDTO addressDTO) {
		UserAddress address = convertToEntity(addressDTO);
		int inserted = userAddressMapper.insertAddress(address);
		if (inserted <= 0) {
			throw new BusinessException(500, "地址添加失败");
		}
	}

	/**
	 * 更新用户地址
	 */
	public void updateAddress(UserAddressDTO addressDTO) {
		Integer id = addressDTO.getId();
		if (id == null) {
			throw new BusinessException(400, "地址 ID 不能为空");
		}
		UserAddress address = convertToEntity(addressDTO);
		address.setId(id);
		int updated = userAddressMapper.updateAddress(address);
		if (updated <= 0) {
			throw new BusinessException(404, "地址更新失败，可能地址不存在");
		}
	}

	/**
	 * 删除用户地址
	 */
	public void deleteAddress(Integer id, Integer userId) {
		if (id == null || userId == null) {
			throw new BusinessException(400, "地址 ID 和用户 ID 不能为空");
		}
		int deleted = userAddressMapper.deleteAddress(id, userId);
		if (deleted <= 0) {
			throw new BusinessException(404, "删除失败，地址不存在");
		}
	}

	/**
	 * 获取用户地址，返回 VO 对象
	 */
	public List<UserAddress> getAddressById(Integer userId) {
		if (userId == null) {
			throw new BusinessException(400, "用户 ID 不能为空");
		}
		List<UserAddress> address = userAddressMapper.getAddressById(userId);
		if (address.isEmpty()) {
			return new ArrayList<>();
		}
		return address;
	}

	/**
	 * 将 DTO 转换为 Entity
	 */
	private UserAddress convertToEntity(UserAddressDTO dto) {
		UserAddress entity = new UserAddress();
		entity.setUserId(dto.getUserId());
		entity.setName(dto.getName());
		entity.setMobile(dto.getMobile());
		entity.setProvinceId(dto.getProvinceId());
		entity.setCityId(dto.getCityId());
		entity.setRegionId(dto.getRegionId());
		entity.setIsDefault(dto.getIsDefault());
		entity.setDetail(dto.getDetail());
		return entity;
	}

	/**
	 * 将 Entity 转换为 VO
	 */
	private UserAddressVO convertToVO(UserAddress address) {
		UserAddressVO vo = new UserAddressVO();
		vo.setId(address.getId());
		vo.setUserId(address.getUserId());
		vo.setName(address.getName());
		vo.setMobile(address.getMobile());
		vo.setProvinceId(address.getProvinceId());
		vo.setCityId(address.getCityId());
		vo.setRegionId(address.getRegionId());
		vo.setDetail(address.getDetail());
		return vo;
	}

	// 获取所有用户地址列表
	public List<UserAddress> getAddressList() {
		return userAddressMapper.getAllAddresses();
	}
}
